using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace Acms.Controls
{
    public class GridViewWithInsert : GridView
    {
        public GridViewWithInsert()
        {
        }

        protected override void OnRowCommand(GridViewCommandEventArgs e)
        {
            Context.Trace.Warn(e.CommandName, e.CommandArgument.ToString());
            if (e.CommandName == "Insert")
            {
                IDataSource data = GetDataSource();
                if (data != null)
                {
                    int i = int.Parse(e.CommandArgument.ToString());
                    System.Collections.Specialized.OrderedDictionary values = new System.Collections.Specialized.OrderedDictionary();
                    DataControlField[] fields = new DataControlField[this.Columns.Count];
                    base.Columns.CopyTo(fields, 0);
                    int n = 0;
                    foreach(DataControlField field in fields)
                    {
                        field.ExtractValuesFromCell(values, insertRow.Cells[n] as DataControlFieldCell, DataControlRowState.Insert, true);
                        n++;
                    }
                    DataSourceViewOperationCallback callback = new DataSourceViewOperationCallback(Inserted);
                    data.GetView("").Insert(values, callback);
                    _insertMode = false;
                    DataBind();
                }
            }
            else if (e.CommandName == "Select")
            {
                _insertMode = false;
                base.EditIndex = -1;
                try
                {
                    base.SelectedIndex = int.Parse(e.CommandArgument as string);
                }
                catch (FormatException)
                {
                    base.SelectedIndex = -1;
                }
                DataBind();
            }
            else
            {
                _insertMode = false;
                base.OnRowCommand(e);
            }
        }

        private bool Inserted(int affectedRecords, Exception e)
        {
            if (e != null)
            {
                throw e;
            }
            return true;
        }

        private bool _allowInsert = true;
        public bool AllowInsert
        {
            get { return _allowInsert; }
            set { _allowInsert = value; }
        }

        private bool _insertMode = false;
        public void StartInsert()
        {
            _insertMode = true;
            DataBind();
        }

        public void EndInsert()
        {
            _insertMode = false;
        }

        private GridViewRow insertRow;
        protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
        {
            int retVal = base.CreateChildControls(dataSource, dataBinding);
            if (_insertMode)
            {
                int i = this.Rows.Count - 1;
                while(this.Rows[i].RowType != DataControlRowType.DataRow && i > 0)
                {
                    i--;
                }
                
                
                DataControlField[] fields = new DataControlField[this.Columns.Count];
                base.Columns.CopyTo(fields, 0);


                Table grid = null;
                if (this.Rows.Count == 0)
                {
                    grid = CreateChildTable();
                    if (ShowHeader)
                    {
                        GridViewRow header = CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
                        base.InitializeRow(header, fields);
                        grid.Rows.Add(header);
                    }
                }
                else
                {
                    grid = (Table)this.Rows[0].Parent;
                }
                int rowIndex = this.Rows.Count + 1;
                insertRow = CreateRow(i + 1, -1, DataControlRowType.DataRow, DataControlRowState.Insert);
                base.InitializeRow(insertRow, fields);
                grid.Rows.AddAt(rowIndex, insertRow);

            }
            return retVal;
        }

        protected override object SaveViewState()
        {
            ViewState["InsertMode"] = _insertMode;
            return base.SaveViewState();
        }

        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
            if (ViewState["InsertMode"] is bool)
            {
                _insertMode = (bool)ViewState["InsertMode"];
            }
        }

        protected override GridViewRow CreateRow(int rowIndex, int dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState)
        {
            if ((rowState & DataControlRowState.Insert) > 0)
            {
                GridViewRow row = new GridViewRow(rowIndex, dataSourceIndex, rowType, rowState);
                /*foreach(DataControlField field in this.Columns)
                {
                    //DataControlFieldCell cell = new DataControlFieldCell(field);
                    //field.InitializeCell(cell, DataControlCellType.DataCell, DataControlRowState.Edit, rowIndex);
                    //row.Cells.Add(cell);
                }*/
                return row;

            }
            else
            {
                return base.CreateRow(rowIndex, dataSourceIndex, rowType, rowState);
            }
        }

        protected override void InitializeRow(GridViewRow row, DataControlField[] fields)
        {
            if ((row.RowState & DataControlRowState.Insert) > 0)
            {
                foreach(DataControlField field in fields)
                {
                    
                }
            }
            else
            {
                base.InitializeRow(row, fields);
            }
        }

        /*internal enum Commands
        {
            Edit,
            Update,
            Cancel,
            Insert
        }

        internal void RaiseCommand(Commands command, string commandArgument)
        {
        }*/
    }

    public class BoundField : System.Web.UI.WebControls.BoundField
    {
        public override void ExtractValuesFromCell(System.Collections.Specialized.IOrderedDictionary dictionary, DataControlFieldCell cell, DataControlRowState rowState, bool includeReadOnly)
        {
            if (this.Control is GridView && rowState == DataControlRowState.Insert && !this.ReadOnly)
            {
                /*TextBox tb = cell.Controls[0]as TextBox;
                if (tb != null)
                {
                    dictionary[this.DataField] = tb.Text;
                }*/
                base.ExtractValuesFromCell(dictionary, cell, DataControlRowState.Edit, includeReadOnly);
            }
            else
            {
                base.ExtractValuesFromCell(dictionary, cell, rowState, includeReadOnly);
            }
        }

        protected override object GetValue(Control controlContainer)
        {
            return base.GetValue(controlContainer);
        }

        protected override void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)
        {
            if (this.Control is GridView && (rowState & DataControlRowState.Insert) > 0 && (this.ReadOnly || !this.InsertVisible))
            {
            }
            else if (this.Control is GridView && (rowState & DataControlRowState.Insert) > 0 && (!this.ReadOnly || this.InsertVisible))
            {
                /*TextBox tb = new TextBox();
                tb.ID = "Text";
                cell.Controls.Add(tb);*/
                base.InitializeDataCell(cell, DataControlRowState.Edit);
            }
            else
            {
                base.InitializeDataCell(cell, rowState);
            }

            if((rowState & DataControlRowState.Edit) > 0 || (rowState & DataControlRowState.Insert) > 0)
            {
                if (cell.Controls.Count == 1)
                {
                    Control ctrl = cell.Controls[0];
                    if (this.IsRequiredField)
                    {
                        RequiredFieldValidator val = new RequiredFieldValidator();
                        val.ErrorMessage = RequiredErrorMessage;
                        val.ControlToValidate = ctrl.ID;
                    }
                }
            }
        }

        protected override void OnDataBindField(object sender, EventArgs e)
        {
            base.OnDataBindField(sender, e);
        }

        private bool _isRequiredField;
        public bool IsRequiredField
        {
            get { return _isRequiredField; }
            set { _isRequiredField = value; }
        }

        private string _requiredErrorMessage;

        public string RequiredErrorMessage
        {
            get { return _requiredErrorMessage; }
            set { _requiredErrorMessage = value; }
        }
	
    }

    public class CommandField : System.Web.UI.WebControls.CommandField
    {
        public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
        {
            if(cellType == DataControlCellType.DataCell)
            {
                if(((rowState & DataControlRowState.Edit) == 0) && ((rowState & DataControlRowState.Insert) == 0))
                {
                    if ((rowState & DataControlRowState.Selected) == 0)
                    {
                        LinkButton select = new LinkButton();
                        select.CommandName = "Select";
                        select.CommandArgument = rowIndex.ToString();
                        select.Text = "Select";
                        select.Attributes["onclick"] = "return confirm('Are you sure you want to select this record?')";
                        cell.Controls.Add(select);
                        cell.Controls.Add(new LiteralControl(" "));
                    }


                    LinkButton edit = new LinkButton();
                    edit.CommandName = "Edit";
                    edit.CommandArgument = rowIndex.ToString();
                    edit.Text = "Edit";

                    cell.Controls.Add(edit);
                    cell.Controls.Add(new LiteralControl(" "));

                    LinkButton delete = new LinkButton();
                    delete.CommandName = "Delete";
                    delete.CommandArgument = rowIndex.ToString();
                    //delete.Command += new CommandEventHandler(edit_Command);
                    delete.Text = "Delete";
                    delete.Attributes["onclick"] = "return confirm('Are you sure you want to delete this record?')";

                    cell.Controls.Add(delete);
                }
                else if ((rowState & DataControlRowState.Edit) > 0)
                {
                    LinkButton update = new LinkButton();
                    update.CommandName = "Update";
                    update.CommandArgument = rowIndex.ToString();
                    //update.Command += new CommandEventHandler(update_Command);
                    update.Text = "Update";
                    update.Attributes["onclick"] = "return confirm('Are you sure you want to update this record?')";

                    LinkButton cancel = new LinkButton();
                    cancel.CommandName = "Cancel";
                    cancel.CommandArgument = rowIndex.ToString();
                    //cancel.Command += new CommandEventHandler(cancel_Command);
                    cancel.Text = "Cancel";

                    cell.Controls.Add(update);
                    cell.Controls.Add(new LiteralControl(" "));
                    cell.Controls.Add(cancel);
                }
                else if ((rowState & DataControlRowState.Insert) > 0)
                {
                    LinkButton insert = new LinkButton();
                    insert.CommandName = "Insert";
                    insert.CommandArgument = rowIndex.ToString();
                    //insert.Command += new CommandEventHandler(insert_Command);
                    insert.Text = "Insert";
                    insert.Attributes["onclick"] = "return confirm('Are you sure you want to insert this record?')";

                    LinkButton cancel = new LinkButton();
                    cancel.CommandName = "Cancel";
                    cancel.CommandArgument = rowIndex.ToString();
                    //cancel.Command += new CommandEventHandler(cancel_Command);
                    cancel.Text = "Cancel";

                    cell.Controls.Add(insert);
                    cell.Controls.Add(new LiteralControl(" "));
                    cell.Controls.Add(cancel);
                }
                else
                {
                    throw new ApplicationException(rowState.ToString());
                }
            }
        }

/*        void insert_Command(object sender, CommandEventArgs e)
        {
            b
        }

        void cancel_Command(object sender, CommandEventArgs e)
        {
        }

        void update_Command(object sender, CommandEventArgs e)
        {
        }

        void edit_Command(object sender, CommandEventArgs e)
        {
        }
*/
    }


    /*public class CommandField : System.Web.UI.WebControls.CommandField
    {
        public CommandField()
        {
        }

        public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
        {

            if (Control is GridView && rowState == DataControlRowState.Insert && ShowEditButton)
            {
                LinkButton insert = new LinkButton();
                insert.CommandName = "Insert";
                insert.CommandArgument = rowIndex.ToString();
                insert.Text = this.InsertText;
                insert.ToolTip = "Click to insert the record";
                cell.Controls.Add(insert);

                cell.Controls.Add(new System.Web.UI.LiteralControl(" "));

                LinkButton cancel = new LinkButton();
                cancel.CommandName = "Cancel";
                cancel.CommandArgument = rowIndex.ToString();
                cancel.Text = this.CancelText;
                cancel.ToolTip = "Click to cancel";
                cell.Controls.Add(cancel);
            }
            else
            {
                base.InitializeCell(cell, cellType, rowState, rowIndex);
            }
        }
    }*/
}
